package org.rjxh.examfront.service.impl;

import com.alibaba.fastjson.JSON;
import org.rjxh.examfront.pojo.*;
import org.rjxh.examfront.mapper.ExamRespondMapper;
import org.rjxh.examfront.service.IExamRespondService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.rjxh.examfront.web.tools.RedisCache;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 考生作答 服务实现类
 * </p>
 *
 * @author BA7LGJ
 * @since 2024-04-04
 */
@Service
public class ExamRespondServiceImpl extends ServiceImpl<ExamRespondMapper, ExamRespond> implements IExamRespondService {

    @Resource
    private RedisCache redisCache;



    @Override
    public R<?> updateResponds(List<ExamRespond> examResponds) {

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long recordId = redisCache.getCacheObject("examRecordingUser:" + loginUser.getUser().getUserId());
        if (recordId == null) {
            return new R<>(500,"当前用户没有正在进行的考试！");
        }

        try {
            examResponds.forEach(examRespond -> {
                examRespond.setRecordId(recordId);
            });


            Map<String, ExamRespond> recordResponds = redisCache.getCacheMap("RecordResponds:" + recordId);
            if (recordResponds != null) {
                for (ExamRespond examRespond : examResponds) {
                    recordResponds.put(examRespond.getQuestionId().toString(), examRespond);
                }
            }
            redisCache.setCacheMap("RecordResponds:" + recordId, recordResponds);
        } catch (Exception e) {
            return new R<>(500,"操作失败");
        }
        return new R<>(200,"操作成功");
    }


}
